import {
	getNeedLoginPages,
	needLoginPages
} from '@/utils/router/pages'
import { log } from '@/utils/log'
import { useAppStore } from "@/store/app";

// 登录页面路径
const loginRoute = '/pages/index/ceshi'

const isLogin = () => {
	return false
}


const isDev = import.meta.env.DEV

// 黑名单登录拦截器 - （适用于大部分页面不需要登录，少部分页面需要登录）
const navigateToInterceptor = {
	// 注意，这里的url是 '/' 开头的，如 '/pages/index/index'，跟 'pages.json' 里面的 path 不同
	invoke({
		url
	}) {
		const path = url.split('?')[0]

		const isNeedLogin = needLoginPages.includes(path)
		if (!isNeedLogin || isLogin()) {
			const useApp = useAppStore()
			useApp.lastPage = url
			return true
		}
		
		const redirectRoute = `${loginRoute}?redirect=${url}`
		uni.navigateTo({
			url: redirectRoute
		})
		log.success(`路由拦截器`,`由${url}重定向至${redirectRoute}`)
		
		return false
	},
	success(args) {
		
		log.success(`路由拦截器成功回调`,JSON.stringify(args))
	},
	fail(err) {
		log.success(`路由拦截器失败回调`,JSON.stringify(err))
	},
	complete(res) {
	}
}

export const routeInterceptor = {
	install(app, options) {
		uni.addInterceptor('navigateTo', navigateToInterceptor)
		uni.addInterceptor('reLaunch', navigateToInterceptor)
		uni.addInterceptor('redirectTo', navigateToInterceptor)
		uni.addInterceptor('switchTab', navigateToInterceptor)
	}
}